const mongo = require("../../lib/mongo");
const USER = require("../object/user");
const mid = require("../middleware");
const validate = require('koa2-validation');
const Joi = require('joi');
const ctrl = {};
/**
 * 购买套餐
 * 逻辑，获取套餐价格=》获取用户余额=》判断用户余额是否足够=》扣除用户余额=》插入套餐记录=》添加购买记录
 * @param ctx
 * @returns {Promise<void>}
 */
ctrl.buy = async (ctx)=>{
    try{
        let body = ctx.request.body;
        let choosePack = global.package[body.pack];
        let chooseLimit = choosePack.level[body.limit];
        if(!ctx.session.userInfo.money) return await fun.res(ctx, '10010');
        let money = ctx.session.userInfo.money;
        if(money.balance<chooseLimit.cost) return await fun.res(ctx, '10011');
        let choosePackInfo = Object.assign({}, choosePack);
        delete choosePackInfo.level;
        choosePackInfo.level = chooseLimit;
        let wechatUser = new USER(ctx.session.userInfo.openId);
        let userPackList = await wechatUser.buy(choosePackInfo);
        ctx.session.userInfo.money.balance -= chooseLimit.cost;
        ctx.session.userInfo.money.cost = ctx.session.userInfo.money.cost ? ctx.session.userInfo.money.cost + chooseLimit.cost : chooseLimit.cost;
        return await fun.res(ctx, '00000', {userPackList, userInfo:ctx.session.userInfo});
    }catch (e) {
        throw e;
    }
};
module.exports = (_, pre = '/app/api/') =>{
    _.post(pre + 'package/buy', validate({
        body: {
            pack: Joi.number().required(),
            limit: Joi.number().required()
        }
    }), mid.checkLogin, ctrl.buy);
};